<script setup>
import { read } from 'xlsx/xlsx.mjs';
import { computed, ref } from 'vue';
import { FileExcelOutlined } from '@ant-design/icons-vue';
import { toFormData, REQU } from '@/net/requ.js';
import { useTaskAssign } from './api/use-task-assign.js';
import { useQuesAssign } from './api/use-ques-assign.jsx';
import { useFile } from './api/use-file.js';

const props = defineProps(['id']);
const taskId = props.id;

const fileUrls = ref({});
const fileTotal = computed(() => R.compose( R.length, R.keys )(fileUrls.value));
const { loading, taskInfo, dataSource, main, submit } = useTaskAssign({ id: props.id, fileUrls, fileTotal });
const { controller, fileList, countUploaded, uploading, uploadFailedList, handleChange } = useFile(props.id);
const { columns, isAssignedForAll } = useQuesAssign({ dataSource, fileList, fileTotal, countUploaded, uploadFailedList });

function customRequest({ file, onSuccess, onError }) {
  // if (controller.value.signal.aborted) {
  //   ++countUploaded.value;
  //   return;
  // }

  REQU('/upload', {
    // signal: controller.value.signal,
    method: 'POST',
    body: toFormData({
      file,
      scene: 'default',
      filename: '',
      output: 'json2',
      path: taskId,
      code: '',
      auth_token: '',
      submit: 'upload',
    })
  })
  .then(async result => {
    const countURLs = fileTotal.value;
    const dic = await new Promise(resolve => {
      const toDic = ss => ss.reduce((o, s, i) => Object.assign(o, { [i + countURLs]: s }), {});
      const fr = new FileReader();
      fr.readAsArrayBuffer(file.originFileObj || file);
      fr.addEventListener('load', 
        R.compose(
          resolve,
          toDic,
          R.map(R.prop('h')),
          R.slice(0, -1),
          R.prop('Strings'),
          read,
          R.path(['target', 'result'])
        )
      );
    });

    Object.assign(fileUrls.value, dic);
    onSuccess(result, file);
  })
  .catch(error => onError(error))
  .finally(() => ++countUploaded.value);
}

function retry() {
  uploadFailedList.value.forEach(file => {
    file.status = 'uploading';
    customRequest({
      file,
      onSuccess: (ret, file) => file.status = 'done',
      onError: error => file.status = 'error',
    })
  });
}

main();
</script>

<template>
  <div class="task-assign">
    <a-spin :spinning="loading">
      <template v-if="taskInfo">
        <header>
          <h3>任务名称：{{ taskInfo?.taskName || '--' }}</h3>
          <a-button
            v-exist:task="'完成'"
            :disabled="!(0 < fileTotal)"
            type="primary"
            @click="() => submit({ fileUrls: JSON.stringify(fileUrls) })">
            完成
          </a-button>
        </header>

        <a-upload-dragger
          v-model:fileList="fileList"
          multiple
          :show-upload-list="false"
          accept=".xls,.xlsx"
          :custom-request="customRequest"
          @change="handleChange"
        >
          <file-excel-outlined style="margin-bottom: .5em; font-size: 2em; color: rgba(0,0,0,.45)" />
          <p class="ant-upload-hint">将工作簿拖到此处或点击选择，按住 Ctrl 可同时多选</p>
        </a-upload-dragger>

        <div class="sub-bar">
          <a-form-item label="已上传">{{ fileTotal }}</a-form-item>
          <!-- <template v-if="false">
            <a-form-item label="已失败">
              {{ uploadFailedList.length }}
              <a-button>
                <template #icon><redo-outlined></redo-outlined></template>
              </a-button>
            </a-form-item>
          </template> -->
          <template v-if="uploading">上传中...</template>
      
          <a-button
            type="danger"
            @click="() => controller.abort()"
            style="margin-left: auto;">
            取消上传
          </a-button>
        </div>

        <div class="table-container">
          <template v-if="0 < fileTotal && !isAssignedForAll">
            <p class="for-all-tip">请为所有人分配题数</p>
          </template>

          <label>
            <input hidden type="file" accept=".xls,.xlsx" @change="handleChangeXls">
            <a-button
              type="link"
              :disabled="loading"
              @click="event => event.currentTarget.parentElement.click()">
              <template #icon><file-excel-outlined /></template>
              导入
            </a-button>
          </label>

          <a-table
            :pagination="false"
            row-key="userId"
            :data-source="dataSource"
            :columns="columns">        
          </a-table>
        </div>
      </template>
    </a-spin>
  </div>
</template>
